package com.hotel.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotel.common.Result;
import com.hotel.entity.SysRole;
import com.hotel.service.SysRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 系统角色管理控制器
 * 
 * @author Hotel Management Team
 */
@RestController
@RequestMapping("/sys-role")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class SysRoleController {

    private final SysRoleService sysRoleService;

    /**
     * 分页查询角色
     */
    @GetMapping("/list")
    public Result<Page<SysRole>> getRolePage(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status) {
        
        // 构建查询条件
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<SysRole> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.like("role_name", keyword)
                       .or()
                       .like("role_code", keyword)
                       .or()
                       .like("description", keyword);
        }
        
        if (status != null && !status.trim().isEmpty()) {
            queryWrapper.eq("status", status);
        }
        
        queryWrapper.orderByAsc("sort_order")
                   .orderByDesc("create_time");
        
        Page<SysRole> page = new Page<>(current, size);
        Page<SysRole> result = sysRoleService.page(page, queryWrapper);
        
        return Result.success(result);
    }

    /**
     * 获取所有角色（不分页）
     */
    @GetMapping("/all")
    public Result<List<SysRole>> getAllRoles() {
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<SysRole> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("status", "active")
                   .orderByAsc("sort_order");
        
        List<SysRole> roles = sysRoleService.list(queryWrapper);
        return Result.success(roles);
    }

    /**
     * 获取角色详情
     */
    @GetMapping("/{id}")
    public Result<SysRole> getRoleById(@PathVariable Long id) {
        SysRole role = sysRoleService.getById(id);
        if (role != null) {
            return Result.success(role);
        } else {
            return Result.error("角色不存在");
        }
    }

    /**
     * 根据角色编码获取角色
     */
    @GetMapping("/code/{roleCode}")
    public Result<SysRole> getRoleByCode(@PathVariable String roleCode) {
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<SysRole> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("role_code", roleCode);
        
        SysRole role = sysRoleService.getOne(queryWrapper);
        if (role != null) {
            return Result.success(role);
        } else {
            return Result.error("角色不存在");
        }
    }

    /**
     * 创建角色
     */
    @PostMapping
    public Result<Void> createRole(@Valid @RequestBody SysRole role) {
        // 检查角色编码是否已存在
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<SysRole> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("role_code", role.getCode());
        
        if (sysRoleService.count(queryWrapper) > 0) {
            return Result.error("角色编码已存在");
        }
        
        // 设置默认状态
        if (role.getStatus() == null) {
            role.setStatus("active");
        }
        
        boolean success = sysRoleService.save(role);
        if (success) {
            return Result.success("角色创建成功");
        } else {
            return Result.error("角色创建失败");
        }
    }

    /**
     * 更新角色
     */
    @PutMapping("/{id}")
    public Result<Void> updateRole(@PathVariable Long id, @Valid @RequestBody SysRole role) {
        // 检查角色编码是否已被其他角色使用
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<SysRole> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("role_code", role.getCode())
                   .ne("id", id);
        
        if (sysRoleService.count(queryWrapper) > 0) {
            return Result.error("角色编码已存在");
        }
        
        role.setId(id);
        boolean success = sysRoleService.updateById(role);
        if (success) {
            return Result.success("角色更新成功");
        } else {
            return Result.error("角色更新失败");
        }
    }

    /**
     * 删除角色
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteRole(@PathVariable Long id) {
        // 检查角色是否被用户使用
        // 这里需要根据实际的用户角色关联表来检查
        // 暂时简单删除
        
        boolean success = sysRoleService.removeById(id);
        if (success) {
            return Result.success("角色删除成功");
        } else {
            return Result.error("角色删除失败");
        }
    }

    /**
     * 启用角色
     */
    @PutMapping("/{id}/enable")
    public Result<Void> enableRole(@PathVariable Long id) {
        SysRole role = sysRoleService.getById(id);
        if (role == null) {
            return Result.error("角色不存在");
        }
        
        role.setStatus("active");
        boolean success = sysRoleService.updateById(role);
        if (success) {
            return Result.success("角色启用成功");
        } else {
            return Result.error("角色启用失败");
        }
    }

    /**
     * 禁用角色
     */
    @PutMapping("/{id}/disable")
    public Result<Void> disableRole(@PathVariable Long id) {
        SysRole role = sysRoleService.getById(id);
        if (role == null) {
            return Result.error("角色不存在");
        }
        
        role.setStatus("inactive");
        boolean success = sysRoleService.updateById(role);
        if (success) {
            return Result.success("角色禁用成功");
        } else {
            return Result.error("角色禁用失败");
        }
    }

    /**
     * 获取启用的角色
     */
    @GetMapping("/active")
    public Result<List<SysRole>> getActiveRoles() {
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<SysRole> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("status", "active")
                   .orderByAsc("sort_order");
        
        List<SysRole> roles = sysRoleService.list(queryWrapper);
        return Result.success(roles);
    }

    /**
     * 更新角色排序
     */
    @PutMapping("/{id}/sort")
    public Result<Void> updateRoleSort(@PathVariable Long id, @RequestParam Integer sortOrder) {
        SysRole role = sysRoleService.getById(id);
        if (role == null) {
            return Result.error("角色不存在");
        }
        
        role.setSortOrder(sortOrder);
        boolean success = sysRoleService.updateById(role);
        if (success) {
            return Result.success("排序更新成功");
        } else {
            return Result.error("排序更新失败");
        }
    }

    /**
     * 批量删除角色
     */
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteRoles(@RequestParam List<Long> ids) {
        boolean success = sysRoleService.removeByIds(ids);
        if (success) {
            return Result.success("批量删除成功");
        } else {
            return Result.error("批量删除失败");
        }
    }

    /**
     * 获取角色统计信息
     */
    @GetMapping("/stats")
    public Result<java.util.Map<String, Object>> getRoleStats() {
        java.util.Map<String, Object> stats = new java.util.HashMap<>();
        
        // 总角色数
        long totalRoles = sysRoleService.count();
        stats.put("totalRoles", totalRoles);
        
        // 启用角色数
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<SysRole> activeWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        activeWrapper.eq("status", "active");
        long activeRoles = sysRoleService.count(activeWrapper);
        stats.put("activeRoles", activeRoles);
        
        // 禁用角色数
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<SysRole> inactiveWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        inactiveWrapper.eq("status", "inactive");
        long inactiveRoles = sysRoleService.count(inactiveWrapper);
        stats.put("inactiveRoles", inactiveRoles);
        
        return Result.success(stats);
    }
}